<template>
  <div>
    <div ref="chartContainer" :style="{ width: '100%', height: '300px' }" />
  </div>
</template>

<script setup>
import { dataURLtoBlob } from "@/utils/common";
import * as echarts from "echarts";
import { computed, onUnmounted, ref, watch, onBeforeUnmount, onMounted } from "vue";
const emit = defineEmits(["drillRight"]);
// Chart 实例
let chartInstance = null;
const chartContainer = ref(null);
const props = defineProps({
  rightBarData: {
    type: Array,
    required: true
  },
  rightBarList: {
    type: Object,
    required: true
  }
});

const options = computed(() => {
  return {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    xAxis: {
      type: "value"
    },
    yAxis: {
      type: "category",
      data: props.rightBarList.typeNameValue.reverse()
      // data: props.rightBarList.typeNameValue
    },
    color: ["#4786FF", "#14C7C7 "],
    legend: {},
    grid: {
      left: "3%",
      right: "4%",
      bottom: "0%",
      containLabel: true
    },
    series: props.rightBarData
  };
});
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    chartInstance.setOption(options.value);
    updateChart();
    bindEvents();
  }
};

watch(
  () => props.rightBarData,
  rightBarData => {
    initChart();
    if (chartInstance) {
      updateChart();
      chartInstance.resize();
    }
  },
  { deep: true }
);
onUnmounted(() => {
  chartInstance && chartInstance.dispose();
});
onMounted(() => {
  addResizeListener();
});
onBeforeUnmount(() => {
  removeResizeListener();
  if (chartInstance) {
    chartInstance?.dispose();
  }
});
// 自适应函数（带防抖）
const handleResize = () => {
  if (chartInstance) {
    chartInstance?.resize();
  }
};

// 添加事件监听
const addResizeListener = () => {
  window.addEventListener("resize", handleResize);
};

// 移除事件监听
const removeResizeListener = () => {
  window.removeEventListener("resize", handleResize);
};

//下钻
// 更新图表配置
const updateChart = () => {
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    xAxis: {
      type: "value"
    },
    yAxis: {
      type: "category",
      // data: props.rightBarList.typeNameValue
      data: props.rightBarList.typeNameValue.reverse()
    },
    color: ["#4786FF", "#14C7C7 "],
    legend: {},
    grid: {
      left: "3%",
      right: "4%",
      bottom: "0%",
      containLabel: true
    },
    series: props.rightBarData
  };

  chartInstance.setOption(option, true);
};
// 绑定图表事件
const bindEvents = () => {
  chartInstance.off("click");
  chartInstance.on("click", params => {
    const clickedNode = props.rightBarList.typeCodeValue[params.dataIndex];
    emit("drillRight", clickedNode); // 触发下钻事件
  });
};
</script>
